package com.bestcem.xm.user.controller;

import com.bestcem.xm.common.core.constant.RegTypes;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.common.core.domain.web.XmViewResultJson;
import com.bestcem.xm.common.core.enums.ReqErrorCodeEnum;
import com.bestcem.xm.common.core.uitls.SignUtil;
import com.bestcem.xm.component.security.annotation.AuthIgnore;
import com.bestcem.xm.user.config.UserSignConfig;
import com.bestcem.xm.user.controller.param.UpdateUnsubscribeSettingParam;
import com.bestcem.xm.user.controller.vo.GetUnsubscribeSettingVO;
import com.bestcem.xm.user.controller.vo.UpdateUnsubscribeSettingVO;
import com.bestcem.xm.user.service.UnsubscribeSettingService;
import com.bestcem.xm.user.service.dto.setting.UnsubscribeSettingDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import java.util.HashMap;
import java.util.Map;

/**
 * 退订设置controller
 *
 * @author ympan <yuming.pan@idiaoyan.com>
 * @version v1.0
 * @date 2022/7/12 14:13
 */
@Slf4j
@Validated
@RestController
@RequestMapping(value = "/user/unsubscribe_setting")
public class UnsubscribeSettingController {
    @Resource
    private UnsubscribeSettingService unsubscribeSettingService;

    @Resource
    private UserSignConfig userSignConfig;

    /**
     * 获取退订设置
     *
     * @return 退订设置VO
     * @author ympan <yuming.pan@idiaoyan.com>
     * @date 18:11 2022/7/12
     */
    @GetMapping("/")
    public XmViewResultJson<GetUnsubscribeSettingVO> getByOrgId(HttpServletRequest request) {
        String orgId = String.valueOf(request.getAttribute("orgId"));
        ServiceResult<UnsubscribeSettingDTO> result = unsubscribeSettingService.getByOrgId(orgId);
        if (!result.isSuccess()) {
            return XmViewResultJson.fail(Integer.valueOf(result.getErrorCode()), result.getMsg());
        }
        return XmViewResultJson.success(UnsubscribeSettingDTO.dto2Vo(result.getData()));
    }

    /**
     * 获取退订设置，无需鉴权，但需要验签
     *
     * @param orgId 公司id
     * @param sig   签名
     * @return 退订设置VO
     * @author ympan <yuming.pan@idiaoyan.com>
     * @date 14:11 2022/7/14
     */
    @GetMapping("/{org_id}")
    @AuthIgnore
    public XmViewResultJson<GetUnsubscribeSettingVO> getByOrgIdAndSig(@PathVariable("org_id")
                                                                      @NotBlank(message = "公司id不能为空") @Pattern(regexp = RegTypes.OBJECT_ID, message = "公司id格式错误")
                                                                      String orgId,
                                                                      @RequestParam("sig")
                                                                      @NotBlank(message = "签名不能为空") @Pattern(regexp = RegTypes.SIGNATURE, message = "签名格式错误")
                                                                      String sig) {
        // 验签
        Map<String, Object> map = new HashMap<>(16);
        map.put("orgId", orgId);
        map.put("sig", sig);
        boolean flag = SignUtil.checkSign(map, userSignConfig.getSettingKey());
        if (!flag) {
            return XmViewResultJson.fail(ReqErrorCodeEnum.SIGN_ERROR.getCode(), "签名不合法");
        }
        ServiceResult<UnsubscribeSettingDTO> result = unsubscribeSettingService.getByOrgId(orgId);
        if (!result.isSuccess()) {
            return XmViewResultJson.fail(Integer.valueOf(result.getErrorCode()), result.getMsg());
        }
        return XmViewResultJson.success(UnsubscribeSettingDTO.dto2Vo(result.getData()));
    }

    /**
     * 更新退订设置
     *
     * @param param 更新退订设置参数
     * @return 退订设置id
     * @author ympan <yuming.pan@idiaoyan.com>
     * @date 14:16 2022/7/12
     */
    @PutMapping("/")
    public XmViewResultJson<UpdateUnsubscribeSettingVO> updateUnsubscribeSetting(@Valid @RequestBody UpdateUnsubscribeSettingParam param, HttpServletRequest request) {
        String orgId = String.valueOf(request.getAttribute("orgId"));
        String userId = String.valueOf(request.getAttribute("userId"));
        param.setOrgId(orgId);
        param.setUserId(userId);
        XmViewResultJson<UpdateUnsubscribeSettingVO> validResult = param.valid();
        if (!validResult.isSuccess()) {
            return validResult;
        }
        ServiceResult<String> result = unsubscribeSettingService.updateUnsubscribeSetting(param);
        if (!result.isSuccess()) {
            return XmViewResultJson.fail(Integer.valueOf(result.getErrorCode()), result.getMsg());
        }
        return XmViewResultJson.success(new UpdateUnsubscribeSettingVO(result.getData()));
    }
}
    